package com.ysstech.system.controller;


import javax.servlet.http.HttpServletRequest;

import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.entity.User;
import com.ysstech.common.enums.YssEnum;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.TokenUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.common.util.verifyutil.VerifyCodeInfo;
import com.ysstech.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
@Api(tags = "用户登录模块api")
@RequestMapping(value = "/userlogin")
public class UserLoginController extends BaseController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户首页页面跳转")
    @YssLog(module = "登录管理", remark = "用户首页页面跳转")
    @RequestMapping(value = "/index")
    public String index(HttpServletRequest request, String kickout) throws Exception {
        log.info("进入方法，跳转页面到首页");
        if (StringUtils.isNotBlank(kickout)) {
            request.setAttribute("kickout", kickout);
        }
        return "index";
    }


    @ApiOperation(value = "用户登录页面跳转")
    @YssLog(module = "登录管理", remark = "用户登录方法")
    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, String kickout) throws Exception {
        log.info("进入方法，跳转页面到登录页面");
        if (StringUtils.isNotBlank(kickout)) {
            request.setAttribute("kickout", kickout);
        }
        request.setAttribute("footerMsg", YssEnum.FOOTER_MSG.getDesc());
        return "login2";
    }

    @ApiOperation(value = "用户注册页面跳转")
    @YssLog(module = "系统管理", remark = "用户注册页面跳转")
    @RequestMapping(value = "/register")
    public String register() {
        log.info("进入方法，跳转页面到注册页面");
        return "register";
    }

    /**
     * 用户登录的方法
     *
     * @param code
     * @param user
     * @return
     */
    @ApiOperation(value = "用户登录的方法")
    @YssLog(module = "登录管理", remark = "用户登录方法")
    @PostMapping(value = "/loginExc")
    @ResponseBody
    public RestResult loginExc(String code, User user) throws Exception {
        Session session = SecurityUtils.getSubject().getSession();
        //判断验证码是否正确
        //String verifyCode = (String) session.getAttribute("verifyCode");
        // Long expireTime = (Long) session.getAttribute("expireTime");
        VerifyCodeInfo verifyCode = (VerifyCodeInfo) session.getAttribute("verifyCode");
        if (null == verifyCode) {
            throw new BusinessException("验证码错误，请重新输入！");
        }
        long currTime = System.currentTimeMillis();
        if (currTime > verifyCode.expireTime) {
            log.info("验证码过期:" + code);
            throw new BusinessException("验证码过期，请重新输入！");
        }
        if (code.equals(verifyCode.verifyCode)) {
            session.removeAttribute("verifycode");
            user = userService.login(user);
            return ResultGenerator.getSuccessResult("登录成功！", user);
        } else {
            log.info("验证码输入错误:" + code + "(" + verifyCode.verifyCode + ")");
            throw new BusinessException("验证码输入错误，请重新输入！");
        }
    }


    @ApiOperation(value = "用户登录的方法")
    @YssLog(module = "登录管理", remark = "用户登录方法")
    @PostMapping(value = "/getUserInfo")
    @ResponseBody
    public RestResult getUserInfo(String token) throws Exception {
        String userId = TokenUtil.getKey(token);
        User user = userService.getById(userId);
        Map<String, Object> map = new HashMap<>();
        /**
         * name: 'super_admin',
         *     user_id: '1',
         *     access: ['super_admin', 'admin'],
         *     token: 'super_admin',
         *     avatar: 'https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png'
         */
        map.put("user", "user");
        map.put("name", "super_admin");
        map.put("user_id", "1");
        map.put("token", "token");
        map.put("access", new String[]{"super_admin", "admin"});
        map.put("avatar", "https://file.iviewui.com/dist/a0e88e83800f138b94d2414621bd9704.png");
        return ResultGenerator.getSuccessResult("登录成功！", map);
    }


    /**
     * 退出登录的方法
     *
     * @return
     */
    @ApiOperation(value = "退出登陆")
    @YssLog(module = "登录管理", remark = "退出登陆")
    @RequestMapping(value = "/logout")
    public String loginOut(HttpServletRequest request) throws Exception {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        request.setAttribute("footerMsg", YssEnum.FOOTER_MSG.getDesc());
        return "login2";
    }

    @ApiOperation(value = "跳转404页面")
    @YssLog(module = "登录管理", remark = "跳转404页面")
    @RequestMapping(value = "/404")
    public String init404() throws Exception {
        return "404";
    }

    @ApiOperation(value = "跳转401页面")
    @YssLog(module = "登录管理", remark = "跳转401页面")
    @RequestMapping(value = "/401")
    public String init401() throws Exception {
        return "401";
    }

    @ApiOperation(value = "跳转404页面")
    @YssLog(module = "登录管理", remark = "跳转404页面")
    @RequestMapping(value = "/500")
    public String init500() throws Exception {
        return "404";
    }
}
